/**   
 * @{#} ClimbByStage.java Create on 2013-7-23 下午3:22:34   
 *   
 * Copyright (c) 2012 by Baidu.   
 */
package union.func;

import java.util.HashMap;
import java.util.List;

import objtable.core.IntKeyGen;
import objtable.core.TableGenerator;
import objtable.port.DbPort;
import objtable.struct.DataType;
import objtable.struct.Row;

/**
 * @author <a href="mailto:zhangbo07@baidu.com">zhangbo07</a>
 * @version 1.0
 */

public class DomainQualityRate {

	HashMap<Integer, Row> hm = new HashMap<Integer, Row>(200000);
	double qualityDivide = 0;

	public DomainQualityRate(DbPort db) {
		qualityDivide = Double.parseDouble(db.oneValueQuery(
				"select s.value from sysnvtab s where s.name='qualityDivide'")
				.toString());

		String date = (String) db
				.oneValueQuery("select max(countdate) from daywebsiteshowquality");

		TableGenerator tg = new TableGenerator("domainquality"
				+ IntKeyGen.nextInt()).addField(DataType.INT, "tm")
				.addField(DataType.INT, "showquality")
				.addField(DataType.DOUBLE, "divide");// 默认值是0
		List<Row> r = db
				.fromDB(tg,
						"select um.id as tm,ifnull(q.showQuality,2) as showquality,ifnull(pld.divide,0) as divide from UnionMedium um left join DayWebsiteShowQuality q on um.maindomain=q.domain and q.countdate='"
								+ date
								+ "' left join daywebsitequalitylevelsttt dq on um.maindomain = dq.maindomain and dq.countdate='"
								+ date
								+ "' left join pfsleveltodivide pld on dq.level = pld.level");
		init(r);
	}

	public void init(List<Row> rows) {
		for (Row r : rows) {
			hm.put(r.getInt("tm"), r);
		}
	}

	public double qualityrate(int tm) {
		Row r = hm.get(tm);
		// 如果没有网站质量信息
		if (r == null) {
			return query(2, 1.0d);
		} else {
			return query(r.getInt("showquality"), r.getDouble("divide"));
		}
	}

	private double query(int qualityStar, double pfsDivide) {
		double award = 0;
		double cutdown = 1;

		switch (qualityStar) {
		case 1:
			cutdown = (pfsDivide == 0 ? 0.9 : pfsDivide);
			break;
		case 3:
			award = qualityDivide;
			break;
		}
		return (1 + award) * cutdown;
	}
}
